//
//  MapViewController.m
//  SXH
//
//  Created by 房 国生 on 15/6/24.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "MapViewController.h"
#import "CommonService.h"
#import "SpotEntity.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "YYAnimationIndicator.h"
#import "SpotDetailViewController.h"
#import "BasicMapAnnotation.h"
#import "DXAlertView.h"
#import "DBManager.h"

@interface MapViewController ()
{
    YYAnimationIndicator *indicator;
    int zoom;
}
@property (nonatomic, strong) NSMutableArray *mutableArraySpot;
@property (nonatomic, strong) IBOutlet UIButton *btnSpot;
@property (nonatomic, strong) IBOutlet UIButton *btnSpotText;
@property (nonatomic, strong) IBOutlet UIButton *btnBusiness;
@property (nonatomic, strong) IBOutlet UIButton *btnBusinessText;
@property (nonatomic, strong) IBOutlet UIButton *btnToilet;
@property (nonatomic, strong) IBOutlet UIButton *btnToiletText;
@property (nonatomic, strong) IBOutlet UIButton *btnOther;
@property (nonatomic, strong) IBOutlet UIButton *btnOtherText;
@property (nonatomic, strong) IBOutlet UIButton *btnRoute;
@property (nonatomic, strong) IBOutlet UIButton *btnRouteText;

@end

@implementation MapViewController
@synthesize mutableArraySpot;
@synthesize btnBusiness, btnBusinessText, btnOther, btnOtherText;
@synthesize btnRoute, btnRouteText, btnSpot, btnSpotText, btnToilet;
@synthesize btnToiletText;
@synthesize parkEntity;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"地图";
    mutableArraySpot = [[NSMutableArray alloc] init];
    
    _locService = [[BMKLocationService alloc]init];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _locService.delegate = self;
    zoom = 15;
    [_mapView setZoomLevel:zoom];
    
    
    if ([[AppDelegate instance].arraySpot count] == 0) {
        indicator = [[YYAnimationIndicator alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-40, self.view.frame.size.height/2-40, 80, 57)];
        [indicator setLoadText:@"正在加载..."];
        [self.view addSubview:indicator];
        
        [indicator startAnimation];  //开始转动
        
        ParkEntity *entity = [DBManager selectParkByParkId:parkEntity.ID];
        if (entity != nil) {
            CommonService *service = [[CommonService alloc] init];
            [service getSpotDataFromLocal:entity.ID];
        } else {
            [self getSpotFromInternetData];
        }
    } else {
        [self setAnnotionsWithList:@"1"];
    }
}

-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _locService.delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _locService.delegate = nil;
}


- (void) setAnnotionsWithList:(NSString *)pType {
    
    [_mapView removeAnnotations:mutableArraySpot];
    
    [mutableArraySpot removeAllObjects];
    
    for (int i = 0; i < [[AppDelegate instance].arraySpot count]; i++) {
        SpotEntity *entity = [[AppDelegate instance].arraySpot objectAtIndex:i];
        
        if ([pType isEqualToString:entity.ptype] == YES) {
            CLLocationDegrees latitude = [entity.y doubleValue];
            CLLocationDegrees longtitude = [entity.x doubleValue];
            
            BasicMapAnnotation *annotiation = [[BasicMapAnnotation alloc] initMapAnnotation:latitude
                                                                               andLongitude:longtitude
                                                                                    Address:entity.content
                                                                                       Name:entity.title
                                                                                      Ptype:entity.ptype
                                                                              andInfoNumber:i];
            [mutableArraySpot addObject:annotiation];
            
            DebugLog(@"%@,%@,%@", entity.ptype,entity.x, entity.y);
            
            if (i == 0) {
                CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longtitude];
                [_mapView setCenterCoordinate:location.coordinate animated:YES];
            }
            [_mapView addAnnotation:annotiation];
        }
    }
}

-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation{
    static NSString *indentifier=@"basicMapAnnotation";
    if ([annotation isKindOfClass:[BasicMapAnnotation class]]) {
        BMKAnnotationView *annView=[mapView dequeueReusableAnnotationViewWithIdentifier:indentifier];
        if (!annView) {
            annView=[[BMKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:indentifier];
        }
        annView.canShowCallout = NO;//在点击大头针的时候会弹出那个黑框框
        annView.draggable = NO;//这里决定annView能不能拖动，应该经常会把它设为NO
        
        BasicMapAnnotation *an = (BasicMapAnnotation *)annotation;
        
        if ([an.ptype isEqualToString:@"1"] == YES) {
            annView.image = [UIImage imageNamed:@"地图图标_景点@2x"];
        } else if ([an.ptype isEqualToString:@"2"] == YES) {
            annView.image = [UIImage imageNamed:@"地图图标_商业@2x"];
        } else if ([an.ptype isEqualToString:@"3"] == YES) {
            annView.image = [UIImage imageNamed:@"地图图标_厕所@2x"];
        }
        
        for (UIView *view in [annView subviews]) {
            [view removeFromSuperview];
        }
        
        return annView;
    } else {
        BMKAnnotationView *annView=[mapView dequeueReusableAnnotationViewWithIdentifier:indentifier];
        return annView;
    }
}

-(void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view{
    BasicMapAnnotation *basicAnnotation=(BasicMapAnnotation *)view.annotation;
    NSString *strContent = [NSString stringWithFormat:@"%@", basicAnnotation.address];
    
    DXAlertView *alert = [[DXAlertView alloc] initWithTitle:basicAnnotation.name contentText:strContent leftButtonTitle:@"取消" rightButtonTitle:@"确定"];
    [alert show];
    alert.leftBlock = ^() {
        NSLog(@"left button clicked");
    };
    alert.rightBlock = ^() {
        NSLog(@"right button clicked");
        SpotEntity *entity = [[AppDelegate instance].arraySpot objectAtIndex:basicAnnotation.number];
        SpotDetailViewController *vc = [[SpotDetailViewController alloc] init];
        vc.musicArray = [AppDelegate instance].arraySpot;
        vc.entity = entity;
        [self.navigationController pushViewController:vc animated:YES];
    };
    alert.dismissBlock = ^() {
        NSLog(@"Do something interesting after dismiss block");
    };
}

-(void)mapView:(BMKMapView *)mapView didDeselectAnnotationView:(BMKAnnotationView *)view{
    NSLog(@"deselect");
}

/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
- (void)mapViewWillStartLocatingUser:(BMKMapView *)mapView
{
    NSLog(@"start locate");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    NSLog(@"didUpdateUserHeading lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    NSLog(@"heading is %@",userLocation.heading);
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
//- (void)didUpdateUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    [_mapView updateLocationData:userLocation];
    [_mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    
    //[mainVC getCinemaData:userLocation.location.coordinate.latitude  Lon:userLocation.location.coordinate.longitude];
    
    [_locService stopUserLocationService];
}

/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)mapViewDidStopLocatingUser:(BMKMapView *)mapView
{
    NSLog(@"stop locate");
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)mapView:(BMKMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}

- (void) getSpotFromInternetData {
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           parkEntity.ID, @"parkid", nil];
    
    [service getNetWorkData:param
                       Path:SPOTPATH
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSArray *array = [dic objectForKey:@"attractionRows"];
                      
                      for (NSDictionary* attributes in array) {
                          SpotEntity *entity2 = [[SpotEntity alloc] init];
                          entity2 = [entity2 initWithAttributes:attributes];
                          [[AppDelegate instance].arraySpot addObject:entity2];
                      }
                      
                      array = [dic objectForKey:@"businessRows"];
                      
                      for (NSDictionary* attributes in array) {
                          SpotEntity *entity2 = [[SpotEntity alloc] init];
                          entity2 = [entity2 initWithAttributes:attributes];
                          [[AppDelegate instance].arrayBusiness addObject:entity2];
                      }
                      
                      array = [dic objectForKey:@"toiletRows"];
                      
                      for (NSDictionary* attributes in array) {
                          SpotEntity *entity2 = [[SpotEntity alloc] init];
                          entity2 = [entity2 initWithAttributes:attributes];
                          [[AppDelegate instance].arrayToilet addObject:entity2];
                      }
                      [self setAnnotionsWithList:@"1"];
                      
                      [indicator stopAnimationWithLoadText:@"加载完成..." withType:YES];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [indicator stopAnimationWithLoadText:@"加载完成..." withType:YES];
                  }];
}

- (IBAction)doSpotAction:(id)sender {
    [self initBottomView:0];
    [self setAnnotionsWithList:@"1"];
}

- (IBAction)doBusinessAction:(id)sender {
    [self initBottomView:1];
    [self setAnnotionsWithList:@"2"];
}

- (IBAction)doToiletAction:(id)sender {
    [self initBottomView:2];
    [self setAnnotionsWithList:@"3"];
}

- (IBAction)doRouteAction:(id)sender {
    [self initBottomView:4];
}

- (void)initBottomView:(int) tab {
    
    if (tab == 0) {
        
        [btnSpot setBackgroundImage:[UIImage imageNamed:@"地图_13"] forState:UIControlStateNormal];
        [btnBusiness setBackgroundImage:[UIImage imageNamed:@"地图_14"] forState:UIControlStateNormal];
        [btnToilet setBackgroundImage:[UIImage imageNamed:@"地图_15"] forState:UIControlStateNormal];
        [btnOther setBackgroundImage:[UIImage imageNamed:@"地图_16"] forState:UIControlStateNormal];
        [btnRoute setBackgroundImage:[UIImage imageNamed:@"地图_17"] forState:UIControlStateNormal];
        
        btnSpotText.titleLabel.textColor = [UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1];
        btnBusinessText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnToiletText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnOtherText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnRouteText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        
    } else if (tab == 1) {
        [btnSpot setBackgroundImage:[UIImage imageNamed:@"地图_03"] forState:UIControlStateNormal];
        [btnBusiness setBackgroundImage:[UIImage imageNamed:@"地图_05"] forState:UIControlStateNormal];
        [btnToilet setBackgroundImage:[UIImage imageNamed:@"地图_15"] forState:UIControlStateNormal];
        [btnOther setBackgroundImage:[UIImage imageNamed:@"地图_16"] forState:UIControlStateNormal];
        [btnRoute setBackgroundImage:[UIImage imageNamed:@"地图_17"] forState:UIControlStateNormal];
        
        btnSpotText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnBusinessText.titleLabel.textColor = [UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1];
        btnToiletText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnOtherText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnRouteText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
    } else if (tab == 2) {
        [btnSpot setBackgroundImage:[UIImage imageNamed:@"地图_03"] forState:UIControlStateNormal];
        [btnBusiness setBackgroundImage:[UIImage imageNamed:@"地图_14"] forState:UIControlStateNormal];
        [btnToilet setBackgroundImage:[UIImage imageNamed:@"地图_07"] forState:UIControlStateNormal];
        [btnOther setBackgroundImage:[UIImage imageNamed:@"地图_16"] forState:UIControlStateNormal];
        [btnRoute setBackgroundImage:[UIImage imageNamed:@"地图_17"] forState:UIControlStateNormal];
        
        btnSpotText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnBusinessText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnToiletText.titleLabel.textColor = [UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1];
        btnOtherText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnRouteText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
    }else if (tab == 3) {
        [btnSpot setBackgroundImage:[UIImage imageNamed:@"地图_03"] forState:UIControlStateNormal];
        [btnBusiness setBackgroundImage:[UIImage imageNamed:@"地图_14"] forState:UIControlStateNormal];
        [btnToilet setBackgroundImage:[UIImage imageNamed:@"地图_15"] forState:UIControlStateNormal];
        [btnOther setBackgroundImage:[UIImage imageNamed:@"地图_09"] forState:UIControlStateNormal];
        [btnRoute setBackgroundImage:[UIImage imageNamed:@"地图_17"] forState:UIControlStateNormal];
        
        btnSpotText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnBusinessText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnToiletText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnOtherText.titleLabel.textColor = [UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1];
        btnRouteText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
    }else if (tab == 4) {
        [btnSpot setBackgroundImage:[UIImage imageNamed:@"地图_03"] forState:UIControlStateNormal];
        [btnBusiness setBackgroundImage:[UIImage imageNamed:@"地图_14"] forState:UIControlStateNormal];
        [btnToilet setBackgroundImage:[UIImage imageNamed:@"地图_15"] forState:UIControlStateNormal];
        [btnOther setBackgroundImage:[UIImage imageNamed:@"地图_16"] forState:UIControlStateNormal];
        [btnRoute setBackgroundImage:[UIImage imageNamed:@"地图_11"] forState:UIControlStateNormal];
        
        btnSpotText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnBusinessText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnToiletText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnOtherText.titleLabel.textColor = [UIColor colorWithRed:0.63 green:0.63 blue:0.63 alpha:1];
        btnRouteText.titleLabel.textColor = [UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1];
    }
}

- (IBAction)showLocation:(id)sender {
    [_locService startUserLocationService];
}

- (IBAction)zoomBig:(id)sender {
    if (zoom++ > 20 ) {
        return;
    }
    [_mapView setZoomLevel:zoom];
}

- (IBAction)zoomSmall:(id)sender {
    if (zoom-- < 10) {
        return;
    }
    [_mapView setZoomLevel:zoom];
}
@end




